﻿using CoreShop.App.Units.Interface;
using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Services;
using Loading;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CoreShop.App
{
    public partial class frmPayAccountList : UIForm
    {
        public PayAccountModel payAccountModel;
        OpaqueCommand cmd = new OpaqueCommand();
        public List<PayAccountModel> ListAIInfo ;
        public frmPayAccountList()
        {
            InitializeComponent();
        }

        public async void LoadData()
        {
            try
            {
                cmd.ShowOpaqueLayer(pnl_Form, 125, true);
                this.dgvAiInfoList.AutoGenerateColumns = false;
                var result = await SystemApiUtil.GetPayAccounList(AppConstVars.sysUser);
                GetPayAccountModel AiListInfo = result.MessageOrString.JsonToEntity<GetPayAccountModel>();
                if (AiListInfo != null && AiListInfo.rows != null && AiListInfo.rows.Count > 0)
                {
                    ListAIInfo = AiListInfo.rows.ToJsonString().JsonToEntity<List<PayAccountModel>>();
                    this.dgvAiInfoList.DataSource = AiListInfo.rows;
                    this.dgvAiInfoList.Focus();
                }
            }
            catch (Exception ex)
            {
                //HideWaitForm();
                ShowSuccessTip("获取卡类型失败:。" + ex.Message);
            }
            finally { cmd.HideOpaqueLayer(); }            
        }

        private void GsGetAiCodeList_Load(object sender, EventArgs e)
        {
            
        }

        private void dgvAiInfoList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvAiInfoList.Rows.Count >= 1)
            {
                btnSelect_Click(null, null);
            }
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            btnSel_Click(null, null);
            //if (dgvAiInfoList.SelectedRows.Count == 1)
            //{
            //    //string aiId = dgvAiInfoList.SelectedRows[0].Cells["aiId"].Value.ToString();
            //    //SelectCurrentAiCodeInfo = ListAIInfo.Find(item =>
            //    //{
            //    //    return (item.aiId == aiId);
            //    //});
            //    //if (SelectCurrentAiCodeInfo != null)
            //     this.DialogResult = DialogResult.Yes;
            //}
        }

        private void ubtn_exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            frmPayAccountInfo fi = new frmPayAccountInfo(ListAIInfo);
            fi.Owner = this;
            fi.ShowDialog();
            fi.Dispose();
            LoadData();
        }

        private void GsGetAiCodeList_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                e.Handled = true;
                if (dgvAiInfoList.Rows.Count >= 1)
                {
                    btnSelect_Click(null, null);
                }
            }
        }

        private async void btnDelte_Click(object sender, EventArgs e)
        {
            if (this.dgvAiInfoList.Rows.Count < 1 && this.dgvAiInfoList.SelectedRows == null && this.dgvAiInfoList.SelectedRows[0] != null)
            {
                return;
            }
            if (!ShowAskDialog("是否删除该条信息？")) return;
            string accountId = this.dgvAiInfoList.SelectedRows[0].Cells["accountId"]?.Value?.ToString() ?? string.Empty;
            if (string.IsNullOrEmpty(accountId))
            {
                MessageBox.Show("没有选择删除行");
                return;
            }
            cmd.ShowOpaqueLayer(pnl_Form, 125, true);
            try
            {
                var accountInfo = ListAIInfo.Find(p => p.accountId == accountId);
                ListAIInfo.Remove(accountInfo);
                int index = 1;
                ListAIInfo.ForEach(p =>
                {
                    p.idx = index;
                    index = index + 1;
                });
                if (ListAIInfo.Count <= 0)
                {
                    ShowInfoTip("至少保留一条账户明细！");
                    return;
                }

                ReturnModel returnModel = await SystemApiUtil.BatchInsertPayInfo(AppConstVars.sysUser, ListAIInfo);
                if (!returnModel.Status.Equals(ReturnStatus.Success))
                {
                    ShowInfoTip("请稍后再试");
                    return;
                }
                ApiReturnModel vipMode = returnModel.MessageOrString.JsonToEntity<ApiReturnModel>();

                if (vipMode.code != 200)
                {
                    ShowInfoTip($"删除失败：{vipMode.msg}");
                    LoadData();
                    return;
                }
                ShowInfoTip($"删除成功！");
                LoadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                cmd.HideOpaqueLayer();
            }
        }

        private void btnSel_Click(object sender, EventArgs e)
        {
           this.DialogResult = DialogResult.OK;
        }

        private void frmPayAccountList_Shown(object sender, EventArgs e)
        {
            LoadData();
        }

        private async void btnSave_Click(object sender, EventArgs e)
        {
            cmd.ShowOpaqueLayer(pnl_Form, 125, true);
            try
            {
                var data = this.dgvAiInfoList.DataSource as List<PayAccountModel>;
                foreach (PayAccountModel model in data)
                {
                    model.accountName = model.appId;
                    model.appSecret = model.appId;
                }

                ReturnModel returnModel = await SystemApiUtil.BatchInsertPayInfo(AppConstVars.sysUser, data);
                if (!returnModel.Status.Equals(ReturnStatus.Success))
                {
                    ShowInfoTip("请稍后再试");
                    return;
                }
                ApiReturnModel vipMode = returnModel.MessageOrString.JsonToEntity<ApiReturnModel>();

                if (vipMode.code != 200)
                {
                    ShowInfoTip($"保存失败：{vipMode.msg}");
                    LoadData();
                    return;
                }
                ShowInfoTip($"保存成功！");
                LoadData();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                cmd.HideOpaqueLayer();
            }            
        }
    }
}
